package com.lingyun.framework.security;

import com.lingyun.common.mapper.LyUserMapper;
import com.lingyun.common.pojo.LyUser;
import com.lingyun.common.utils.StringUtils;
import com.lingyun.common.vo.LoginUser;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 *
 * @author 没事别学JAVA
 *
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private LyUserMapper lyUsermapper;

    @Resource
    private Permission permission;

    /**
     *
     * @param username String
     *
     * @return LyUser 返回当前用户信息
     * */

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException{
        /** 查询用户信息 */
        Map<String,Object> params =new HashMap<>();
        params.put("userName",username);
        LyUser user=lyUsermapper.listLyUser(params);

        /** 判断用户是否存在 */
        if(StringUtils.isEmpty(user)){
            throw new UsernameNotFoundException("用户不存在");
        }
        return createLoginUser(user);
    }

    public UserDetails createLoginUser(LyUser lyUser) {
        Set<String> roles=new HashSet<String>();
        lyUser.getLyRoles().forEach(v ->
                roles.addAll(Arrays.asList(v.getRoleKey().trim()))
        );
        return new LoginUser(lyUser.getUserId(),lyUser,permission.getMenuPermission(lyUser.getUserId(),roles),roles);
    }

}
